import React from 'react';
import { StyleSheet, View, TouchableOpacity, ScrollView, Dimensions } from 'react-native';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';

import { ThemedText } from '@/components/ThemedText';
import { ThemedView } from '@/components/ThemedView';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';

// 模拟健康数据
const HEALTH_DATA = {
  bloodPressure: [
    { date: '10-01', systolic: 125, diastolic: 85 },
    { date: '10-02', systolic: 128, diastolic: 84 },
    { date: '10-03', systolic: 130, diastolic: 86 },
    { date: '10-04', systolic: 126, diastolic: 83 },
    { date: '10-05', systolic: 124, diastolic: 82 },
    { date: '10-06', systolic: 127, diastolic: 84 },
    { date: '10-07', systolic: 129, diastolic: 85 },
  ],
  heartRate: [
    { date: '10-01', value: 72 },
    { date: '10-02', value: 75 },
    { date: '10-03', value: 73 },
    { date: '10-04', value: 70 },
    { date: '10-05', value: 74 },
    { date: '10-06', value: 76 },
    { date: '10-07', value: 72 },
  ],
  bloodSugar: [
    { date: '10-01', value: 5.4 },
    { date: '10-02', value: 5.6 },
    { date: '10-03', value: 5.5 },
    { date: '10-04', value: 5.3 },
    { date: '10-05', value: 5.7 },
    { date: '10-06', value: 5.5 },
    { date: '10-07', value: 5.4 },
  ],
  sleepHours: [
    { date: '10-01', value: 7.5 },
    { date: '10-02', value: 6.8 },
    { date: '10-03', value: 7.2 },
    { date: '10-04', value: 7.0 },
    { date: '10-05', value: 7.5 },
    { date: '10-06', value: 6.5 },
    { date: '10-07', value: 7.8 },
  ],
};

const { width: screenWidth } = Dimensions.get('window');
const chartWidth = screenWidth - 40; // 考虑左右边距

export default function HealthScreen() {
  const colorScheme = useColorScheme();
  const tintColor = Colors[colorScheme ?? 'light'].tint;
  const router = useRouter();

  // 简单的图表渲染函数 - 血压
  const renderBloodPressureChart = () => {
    const maxSystolic = Math.max(...HEALTH_DATA.bloodPressure.map(item => item.systolic));
    const minDiastolic = Math.min(...HEALTH_DATA.bloodPressure.map(item => item.diastolic));
    const range = maxSystolic - minDiastolic + 20; // 添加一些边距
    const barWidth = chartWidth / HEALTH_DATA.bloodPressure.length - 10;

    return (
      <View style={styles.chartContainer}>
        <View style={styles.chartHeader}>
          <ThemedText style={styles.chartTitle}>血压 (mmHg)</ThemedText>
          <TouchableOpacity style={styles.moreButton}>
            <ThemedText style={styles.moreButtonText}>查看详情</ThemedText>
          </TouchableOpacity>
        </View>
        
        <View style={styles.chart}>
          {HEALTH_DATA.bloodPressure.map((item, index) => {
            const systolicHeight = ((item.systolic - minDiastolic) / range) * 100;
            const diastolicHeight = ((item.diastolic - minDiastolic) / range) * 100;
            
            return (
              <View key={index} style={styles.barGroup}>
                <View style={styles.barContainer}>
                  <View style={[styles.systolicBar, { height: systolicHeight }]} />
                  <View style={[styles.diastolicBar, { height: diastolicHeight }]} />
                </View>
                <ThemedText style={styles.barLabel}>{item.date}</ThemedText>
              </View>
            );
          })}
        </View>
        
        <View style={styles.legendContainer}>
          <View style={styles.legendItem}>
            <View style={[styles.legendColor, { backgroundColor: '#FF6B6B' }]} />
            <ThemedText style={styles.legendText}>收缩压</ThemedText>
          </View>
          <View style={styles.legendItem}>
            <View style={[styles.legendColor, { backgroundColor: '#4ECDC4' }]} />
            <ThemedText style={styles.legendText}>舒张压</ThemedText>
          </View>
        </View>
      </View>
    );
  };

  // 简单的图表渲染函数 - 心率
  const renderHeartRateChart = () => {
    const maxValue = Math.max(...HEALTH_DATA.heartRate.map(item => item.value));
    const minValue = Math.min(...HEALTH_DATA.heartRate.map(item => item.value));
    const range = maxValue - minValue + 20; // 添加一些边距

    return (
      <View style={styles.chartContainer}>
        <View style={styles.chartHeader}>
          <ThemedText style={styles.chartTitle}>心率 (bpm)</ThemedText>
          <TouchableOpacity style={styles.moreButton}>
            <ThemedText style={styles.moreButtonText}>查看详情</ThemedText>
          </TouchableOpacity>
        </View>
        
        <View style={styles.lineChart}>
          <View style={styles.lineChartInner}>
            {HEALTH_DATA.heartRate.map((item, index) => {
              const itemHeight = ((item.value - minValue) / range) * 100;
              const left = (index / (HEALTH_DATA.heartRate.length - 1)) * 100;
              
              return (
                <View 
                  key={index} 
                  style={[
                    styles.linePoint,
                    { 
                      bottom: `${itemHeight}%`,
                      left: `${left}%`,
                    }
                  ]}
                />
              );
            })}
            
            {/* 连接线 - 简化版 */}
            <View style={styles.connectingLine} />
          </View>
          
          <View style={styles.lineChartLabels}>
            {HEALTH_DATA.heartRate.map((item, index) => (
              <ThemedText key={index} style={styles.lineChartLabel}>
                {item.date}
              </ThemedText>
            ))}
          </View>
        </View>
      </View>
    );
  };

  // 健康数据卡片
  const renderHealthDataCard = (title, value, unit, icon, color) => (
    <View style={styles.dataCard}>
      <View style={styles.dataCardHeader}>
        <MaterialCommunityIcons name={icon} size={24} color={color} />
        <ThemedText style={styles.dataCardTitle}>{title}</ThemedText>
      </View>
      <View style={styles.dataCardContent}>
        <ThemedText style={styles.dataCardValue}>{value}</ThemedText>
        <ThemedText style={styles.dataCardUnit}>{unit}</ThemedText>
      </View>
    </View>
  );

  return (
    <ThemedView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
          <MaterialCommunityIcons name="arrow-left" size={28} color={tintColor} />
        </TouchableOpacity>
        <ThemedText style={styles.headerTitle}>健康数据</ThemedText>
        <View style={styles.placeholder} />
      </View>
      
      <ScrollView style={styles.scrollView}>
        <View style={styles.todayDataSection}>
          <ThemedText style={styles.sectionTitle}>今日数据</ThemedText>
          <View style={styles.dataCardsContainer}>
            {renderHealthDataCard('血压', '125/85', 'mmHg', 'heart-pulse', '#FF6B6B')}
            {renderHealthDataCard('心率', '72', 'bpm', 'heart', '#4ECDC4')}
            {renderHealthDataCard('血糖', '5.4', 'mmol/L', 'water', '#FFD166')}
            {renderHealthDataCard('睡眠', '7.5', '小时', 'sleep', '#6A0572')}
          </View>
        </View>
        
        <View style={styles.chartsSection}>
          <ThemedText style={styles.sectionTitle}>数据趋势</ThemedText>
          {renderBloodPressureChart()}
          {renderHeartRateChart()}
        </View>
        
        <View style={styles.actionsSection}>
          <TouchableOpacity style={styles.actionButton}>
            <MaterialCommunityIcons name="plus" size={24} color="#fff" />
            <ThemedText style={styles.actionButtonText}>添加数据</ThemedText>
          </TouchableOpacity>
          <TouchableOpacity style={[styles.actionButton, styles.secondaryButton]}>
            <MaterialCommunityIcons name="export" size={24} color={tintColor} />
            <ThemedText style={styles.secondaryButtonText}>导出报告</ThemedText>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingTop: 60,
    paddingBottom: 15,
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#E1E1E1',
  },
  backButton: {
    width: 40,
    height: 40,
    justifyContent: 'center',
    alignItems: 'flex-start',
  },
  headerTitle: {
    fontSize: 22,
    fontWeight: 'bold',
  },
  placeholder: {
    width: 40,
  },
  scrollView: {
    flex: 1,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 15,
    paddingHorizontal: 20,
  },
  todayDataSection: {
    paddingTop: 20,
  },
  dataCardsContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    paddingHorizontal: 20,
    justifyContent: 'space-between',
  },
  dataCard: {
    width: '48%',
    backgroundColor: '#f9f9f9',
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.15,
    shadowRadius: 3,
    elevation: 3,
    borderWidth: 1,
    borderColor: '#e0e0e0',
  },
  dataCardHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 12,
  },
  dataCardTitle: {
    fontSize: 16,
    fontWeight: '500',
    marginLeft: 8,
    color: '#555',
  },
  dataCardContent: {
    flexDirection: 'row',
    alignItems: 'baseline',
  },
  dataCardValue: {
    fontSize: 26,
    fontWeight: 'bold',
    marginRight: 6,
  },
  dataCardUnit: {
    fontSize: 14,
    color: '#666',
  },
  chartsSection: {
    paddingTop: 10,
    paddingBottom: 20,
  },
  chartContainer: {
    backgroundColor: '#f9f9f9',
    borderRadius: 10,
    padding: 15,
    marginHorizontal: 20,
    marginBottom: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 2,
  },
  chartHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 15,
  },
  chartTitle: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  moreButton: {
    padding: 5,
  },
  moreButtonText: {
    fontSize: 14,
    color: '#0a7ea4',
  },
  chart: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-end',
    height: 150,
    marginBottom: 10,
  },
  barGroup: {
    alignItems: 'center',
  },
  barContainer: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    height: 120,
  },
  systolicBar: {
    width: 8,
    backgroundColor: '#FF6B6B',
    borderRadius: 4,
    marginRight: 2
  },
  diastolicBar: {
    width: 8,
    backgroundColor: '#4ECDC4',
    borderRadius: 4,
    marginLeft: 2
  },
  barLabel: {
    fontSize: 12,
    marginTop: 5,
    color: '#666'
  },
  legendContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 10
  },
  legendItem: {
    flexDirection: 'row',
    alignItems: 'center',
    marginHorizontal: 10
  },
  legendColor: {
    width: 12,
    height: 12,
    borderRadius: 6,
    marginRight: 5
  },
  legendText: {
    fontSize: 12,
    color: '#666'
  },
  lineChart: {
    height: 180,
    marginTop: 10
  },
  lineChartInner: {
    height: 150,
    position: 'relative'
  },
  linePoint: {
    width: 10,
    height: 10,
    borderRadius: 5,
    backgroundColor: '#4ECDC4',
    position: 'absolute',
    marginLeft: -5,
    marginBottom: -5
  },
  connectingLine: {
    position: 'absolute',
    height: 2,
    backgroundColor: '#4ECDC4',
    bottom: '50%',
    left: 0,
    right: 0
  },
  lineChartLabels: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 10
  },
  lineChartLabel: {
    fontSize: 12,
    color: '#666',
    textAlign: 'center'
  },
  actionsSection: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: 20,
    paddingBottom: 30
  },
  actionButton: {
    backgroundColor: '#0a7ea4',
    borderRadius: 10,
    paddingVertical: 12,
    paddingHorizontal: 20,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    width: '48%'
  },
  actionButtonText: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: 'bold',
    marginLeft: 8
  },
  secondaryButton: {
    backgroundColor: '#FFFFFF',
    borderWidth: 1,
    borderColor: '#0a7ea4'
  },
  secondaryButtonText: {
    color: '#0a7ea4',
    fontSize: 16,
    fontWeight: 'bold',
    marginLeft: 8
  }
});